// 全局指令注册
import { hasPermission, hasRole } from '@/utils/auth'

// 权限指令
const permission = {
  mounted(el, binding) {
    const { value } = binding
    
    if (value) {
      const hasAuth = hasPermission(value)
      if (!hasAuth) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error('权限指令需要传入权限值')
    }
  },
  updated(el, binding) {
    const { value, oldValue } = binding
    
    if (value !== oldValue) {
      const hasAuth = hasPermission(value)
      if (!hasAuth) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    }
  }
}

// 角色指令
const role = {
  mounted(el, binding) {
    const { value } = binding
    
    if (value) {
      const hasAuth = hasRole(value)
      if (!hasAuth) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error('角色指令需要传入角色值')
    }
  },
  updated(el, binding) {
    const { value, oldValue } = binding
    
    if (value !== oldValue) {
      const hasAuth = hasRole(value)
      if (!hasAuth) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    }
  }
}

// 防抖指令
const debounce = {
  mounted(el, binding) {
    let timer = null
    const { value, arg } = binding
    const delay = arg || 300
    
    el.addEventListener('click', () => {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        value()
      }, delay)
    })
  }
}

// 节流指令
const throttle = {
  mounted(el, binding) {
    let timer = null
    const { value, arg } = binding
    const delay = arg || 300
    
    el.addEventListener('click', () => {
      if (!timer) {
        timer = setTimeout(() => {
          value()
          timer = null
        }, delay)
      }
    })
  }
}

// 复制指令
const copy = {
  mounted(el, binding) {
    el.copyText = binding.value
    el.addEventListener('click', handleCopy)
  },
  updated(el, binding) {
    el.copyText = binding.value
  },
  beforeUnmount(el) {
    el.removeEventListener('click', handleCopy)
  }
}

function handleCopy(e) {
  const text = e.target.copyText
  if (!text) return
  
  if (navigator.clipboard) {
    navigator.clipboard.writeText(text).then(() => {
      ElMessage.success('复制成功')
    }).catch(() => {
      ElMessage.error('复制失败')
    })
  } else {
    // 兼容旧版浏览器
    const textarea = document.createElement('textarea')
    textarea.value = text
    document.body.appendChild(textarea)
    textarea.select()
    try {
      document.execCommand('copy')
      ElMessage.success('复制成功')
    } catch (err) {
      ElMessage.error('复制失败')
    }
    document.body.removeChild(textarea)
  }
}

// 长按指令
const longpress = {
  mounted(el, binding) {
    let timer = null
    const { value, arg } = binding
    const duration = arg || 1000
    
    const start = () => {
      timer = setTimeout(() => {
        value()
      }, duration)
    }
    
    const cancel = () => {
      if (timer) {
        clearTimeout(timer)
        timer = null
      }
    }
    
    el.addEventListener('mousedown', start)
    el.addEventListener('mouseup', cancel)
    el.addEventListener('mouseleave', cancel)
    el.addEventListener('touchstart', start)
    el.addEventListener('touchend', cancel)
    el.addEventListener('touchcancel', cancel)
  }
}

// 拖拽指令
const draggable = {
  mounted(el, binding) {
    el.style.cursor = 'move'
    el.style.position = 'absolute'
    
    let isDragging = false
    let startX, startY, initialX, initialY
    
    const handleMouseDown = (e) => {
      isDragging = true
      startX = e.clientX
      startY = e.clientY
      initialX = el.offsetLeft
      initialY = el.offsetTop
      
      document.addEventListener('mousemove', handleMouseMove)
      document.addEventListener('mouseup', handleMouseUp)
    }
    
    const handleMouseMove = (e) => {
      if (!isDragging) return
      
      const deltaX = e.clientX - startX
      const deltaY = e.clientY - startY
      
      el.style.left = initialX + deltaX + 'px'
      el.style.top = initialY + deltaY + 'px'
    }
    
    const handleMouseUp = () => {
      isDragging = false
      document.removeEventListener('mousemove', handleMouseMove)
      document.removeEventListener('mouseup', handleMouseUp)
      
      if (binding.value && typeof binding.value === 'function') {
        binding.value({
          x: el.offsetLeft,
          y: el.offsetTop
        })
      }
    }
    
    el.addEventListener('mousedown', handleMouseDown)
  }
}

// 懒加载指令
const lazy = {
  mounted(el, binding) {
    const { value } = binding
    
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          if (el.tagName === 'IMG') {
            el.src = value
          } else {
            el.style.backgroundImage = `url(${value})`
          }
          observer.unobserve(el)
        }
      })
    })
    
    observer.observe(el)
  }
}

// 水印指令
const watermark = {
  mounted(el, binding) {
    const { value } = binding
    const text = value || 'ZenithMind'
    
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    
    canvas.width = 200
    canvas.height = 100
    
    ctx.rotate(-20 * Math.PI / 180)
    ctx.font = '16px Arial'
    ctx.fillStyle = 'rgba(0, 0, 0, 0.1)'
    ctx.fillText(text, 10, 50)
    
    const dataURL = canvas.toDataURL()
    
    el.style.position = 'relative'
    el.style.backgroundImage = `url(${dataURL})`
    el.style.backgroundRepeat = 'repeat'
  }
}

// 无限滚动指令
const infiniteScroll = {
  mounted(el, binding) {
    const { value } = binding
    
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting && typeof value === 'function') {
          value()
        }
      })
    })
    
    // 创建一个底部触发元素
    const trigger = document.createElement('div')
    trigger.style.height = '1px'
    el.appendChild(trigger)
    
    observer.observe(trigger)
  }
}

// 点击外部指令
const clickOutside = {
  mounted(el, binding) {
    const { value } = binding
    
    const handleClick = (e) => {
      if (!el.contains(e.target) && typeof value === 'function') {
        value()
      }
    }
    
    document.addEventListener('click', handleClick)
    el._clickOutside = handleClick
  },
  beforeUnmount(el) {
    document.removeEventListener('click', el._clickOutside)
    delete el._clickOutside
  }
}

// 焦点指令
const focus = {
  mounted(el) {
    el.focus()
  }
}

// 自动高度指令（适用于textarea）
const autoHeight = {
  mounted(el) {
    const resize = () => {
      el.style.height = 'auto'
      el.style.height = el.scrollHeight + 'px'
    }
    
    el.addEventListener('input', resize)
    el.addEventListener('change', resize)
    
    // 初始化
    resize()
  }
}

// 设置全局指令
export function setupDirectives(app) {
  app.directive('permission', permission)
  app.directive('role', role)
  app.directive('debounce', debounce)
  app.directive('throttle', throttle)
  app.directive('copy', copy)
  app.directive('longpress', longpress)
  app.directive('draggable', draggable)
  app.directive('lazy', lazy)
  app.directive('watermark', watermark)
  app.directive('infinite-scroll', infiniteScroll)
  app.directive('click-outside', clickOutside)
  app.directive('focus', focus)
  app.directive('auto-height', autoHeight)
}
